<?php

namespace app\api\service;

use app\common\model\AnswerQuestion;
use app\common\model\CollectQuestion;
use app\common\model\Course;
use app\common\model\CourseQuestion;
use app\common\model\CourseQuestionBackground;
use app\common\model\HistoryQuestionDate;
use app\common\model\UserDailyPractice;
use think\facade\Db;

class QuestionService
{
    /**
     * getHistoryQuestionQuery
     * @param array $queryInput
     * @return mixed
     */
    public function getHistoryQuestionQuery(array $queryInput)
    {
        // 初始化
        $id = $type = $userId = $extendId = $questionType = null;
        extract($queryInput);

        // 查询条件
        $where = [
            ['user_id', '=', $userId],
            ['course_id', '=', $id],
            ['question_main_type', '=', $type],
        ];

        // 查询条件
        if ($extendId > 0) {
            $where[] = ['extend_id', '=', $extendId];
        }
        if ($questionType > 0) {
            $where[] = ['question_type', '=', $questionType];
        }

        // 构建查询器
        return app(AnswerQuestion::class)->where($where);
    }

    /**
     * getCourseIdByQuestionId
     * @param $questionId
     * @return int
     */
    public function getCourseIdByQuestionId($questionId): int
    {
        $where = [
            'id' => $questionId
        ];
        return app(CourseQuestion::class)->where($where)->value('course_id', 0);
    }

    /**
     * getQuestionListQuery
     * @param array $queryInput
     * @return mixed
     */
    public function getQuestionListQuery(array $queryInput)
    {
        // 初始化
        $id = $type = $field = $userId = $leftCollect = $leftAnswer = $extendId  = $questionType = null;
        extract($queryInput);

        // 查询条件
        $where = [
            ['a.course_id', '=', $id]
        ];
        if ($questionType > 0) {
            $where[] = ['a.question_type', '=', $questionType];
        }
        if ($type == 1) {
            // 每日一练
            $subWhere = [['uid', '=', $userId], ['course_id', '=', $id]];
            $subQuestionId = app(UserDailyPractice::class)->field('question_id')->where($subWhere)->column('question_id');
            if ($subQuestionId) {
                $where[] = ['a.id', 'in', $subQuestionId];
            } else {
                $where[] = ['a.id', '=', -1];
            }
        }
        if ($type == 2) {
            // 收藏的题
            $subWhere = [['user_id', '=', $userId], ['course_id', '=', $id], ['status', '=', 1],];
            $subQuestionId = app(CollectQuestion::class)->field('question_id')->where($subWhere)->column('question_id');
            if ($subQuestionId) {
                $where[] = ['a.id', 'in', $subQuestionId];
            } else {
                $where[] = ['a.id', '=', -1];
            }
        }
        if ($type == 3) {
            // 答错的题
            $subWhere = [['user_id', '=', $userId], ['course_id', '=', $id], ['status', '=', 2],];
            $subQuestionId = app(AnswerQuestion::class)->where($subWhere)->column('question_id');
            if ($subQuestionId) {
                $where[] = ['a.id', 'in', $subQuestionId];
            } else {
                $where[] = ['a.id', '=', -1];
            }
        }
        if ($type == 8) {
            // 试卷中心
            $where[] = ['a.extend_id', '=', $extendId];
        }

        // 构建查询器
        $query = app(CourseQuestion::class)->alias('a');
        if ($leftCollect) {
            $query->leftJoin('collect_question b', "a.id = b.question_id and b.user_id=$userId and b.status=1");
        }
        if ($leftAnswer) {
            $query->leftJoin(
                'answer_question c',
                "a.id=c.question_id and c.user_id=$userId"
            );
        }
        if ($field) {
            $query->field($field);
        }
        if ($where) {
            $query->where($where);
        }

        return $query;
    }

    /**
     * getQuestionBackgroundByContentId
     * @param $background_id
     * @return mixed
     */
    public function getQuestionBackgroundByContentId($background_id)
    {
        // 查询条件
        $where = [];
        if (is_array($background_id)) {
            $where[] = ['id ', 'in', $background_id];
        } else {
            $where[] = ['id ', 'in', [$background_id]];
        }

        // 查询数据
        return app(CourseQuestionBackground::class)->where($where)->column('value', 'id');
    }

    /**
     * 通过题目id查询是否收藏
     * @param $userId
     * @param $allQuestionId
     * @return mixed
     */
    public function getUserCollectQuestionDict($userId, $allQuestionId)
    {
        // 查询条件
        $where = [
            ['user_id', '=', $userId],
            ['question_id', 'in', $allQuestionId],
        ];

        // 查询数据
        return app(CollectQuestion::class)->where($where)->column('course_id,status', 'question_id');
    }

    /**
     * 通过题目id查询是否错题
     * @param $userId
     * @param $allQuestionId
     * @return mixed
     */
    public function getUserErrorQuestionDict($userId, $allQuestionId)
    {
        // 查询条件
        $where = [
            ['user_id', '=', $userId],
            ['question_id', 'in', $allQuestionId]
        ];

        // 查询数据
        return app(AnswerQuestion::class)->where($where)->column('course_id,status,question_answer', 'question_id');
    }

    /**
     * 通过课程Id集合查询题目数量
     * @param array $courseId
     * @param int $type
     * @return array
     */
    public function getQuestionStaticByCourseId(array $courseId, $type = 0): array
    {
        // 查询条件
        $where = [
            ['course_id', 'in', $courseId],
        ];
        if ($type) {
            $where[] = ['type', '=', $type];
        }

        // 查询字段
        $field = 'course_id,count(*) as count';

        // 查询数据
        $list = app(CourseQuestion::class)->where($where)->field($field)->group('course_id')->cache(true)->select();

        // 返回
        return $list ? $list->toArray() : [];
    }

    /**
     * @param $data
     */
    public function convertData($data)
    {
        //1.合并数组
        $question_data = json_decode($data['question_data'] ?? '', true) ?: [];
        $data = array_merge($data, $question_data);

        //2.如果是选择题,将选项提取出来
        if (!empty($data['answerOption'])) {
            $data = array_merge($data, $data['answerOption']);
        }

        //3.记录用户答题()todo()
        $data['select_answer'] = $data['question_answer'] ?? '';

        //4.清理数据
        unset($data['question_data'], $data['answerOption'], $data['question_answer']);

        //5.错题、收藏题答题记录设置为空,并且设置未答过
        $data['select_answer'] = '';
        $data['is_correct'] = 0;


        //7.处理Img Style
        $this->formatQuestionImgText($data);

        return $data;
    }

    /**
     * formatQuestionImgText
     * @param &$value
     */
    private function formatQuestionImgText(&$value)
    {
        $fields = [
            'A',
            'B',
            'C',
            'D',
            'E',
            'F',
            'explanation',
            'questionAsk',
            'correctOption'
        ];
        //var_dump($value);
        //die();
        foreach ($fields as $field) {
            if (!isset($value[$field])) {
                continue;
            }
            if ($value[$field] == '') {
                continue;
            }
            //var_dump($value[$field]);
            if (strpos($value[$field], 'img') !== false) {
                //var_dump($value[$field]);
                //die();
                $text = $value[$field];
                $pattern = '/<\s*img\s+[^>]*?src\s*=\s*(\'|")(.*?)\\1[^>]*?\/?\s*>/U';
                if (preg_match_all($pattern, $text, $matches)) {
                    //var_dump($matches);
                    $olds = $matches['0'];
                    $news = $matches['2'];
                    foreach ($olds as $key => $old) {
                        $newSrc = $news[$key];
                        $newSrc = str_replace('file.gaojiufeng.cn', 'file.20230611.cn', $newSrc);
                        $newHtml = <<<EOF
<img src="{$newSrc}" style="width: 100%;height: auto" />
EOF;
                        //var_dump($old, $newHtml);
                        $text = str_replace($old, $newHtml, $text);
                    }
                    $value[$field] = $text;
                }
            }
        }
    }
}